#!/bin/sh
# 
# Genera un listado con todos los procesos hijos del proceso llamado.

usage(){
	echo "Informacion de los procesos hijos"
	echo "Uso: $0 -c / -p | <nombre proceso> / <pid>"
}

n_args=2

if [ $# -ne "$n_args" ];
then
	usage
	exit 0
elif [ $1 != "-c" ] && [ $1 != "-p" ];
then
	usage
	exit 0
fi

main_pid=""
main_fname=""
main_ppid=
father_pid=""
father_fname=""


# FIX: Implements version with 1 call only to `ps`
all=`ps -eo pid,comm,ppid | grep -v PID`
all_proc=($all)
n_all_proc=${#all_proc[*]}

k=0	#PID
m=0	#FNAME
j=0	#PPID
n=0	#Counter

for ((i=0; $i<$n_all_proc; ((i=$i+3))));
do
	k=$i
	((m=$i+1))
	((j=$i+2))
	all_proc_pid[$n]=${all_proc[$k]} #PID array
	all_proc_fname[$n]=${all_proc[$m]} #FNAME array
	all_proc_ppid[$n]=${all_proc[$j]} # PPID array
	((n=n+1))
done

n_all_proc_fname=${#all_proc_fname[*]}
n_all_proc_pid=${#all_proc_pid[*]}
n_all_proc_ppid=${#all_proc_ppid[*]}

echo "$n_all_proc_fname"
echo "$n_all_proc_pid"
echo "$n_all_proc_ppid"

if [[ "$1" == "-c" ]]; 
then
	main_fname="$2"
	for ((i=0; $i<$n_all_proc_fname; i++));
	do
		if [[ "${all_proc_fname[$i]}" == "$main_fname" ]];
		then
			main_pid=${all_proc_pid[$i]}
			main_ppid=${all_proc_ppid[$i]}
			father_pid="$main_ppid"
		fi
	done
	if [[ -z "$main_pid" ]] || [[ -z "$main_ppid" ]]; 
	then
		echo "Proceso no encontrado en el sistema"
		exit 0
	fi
elif [[ "$1" == "-p" ]]; 
then
	main_pid="$2"
	for ((i=0; $i<$n_all_proc_pid; i++));
	do
		if [[ "${all_proc_pid[$i]}" -eq "$main_pid" ]];
		then
			main_fname=${all_proc_fname[$i]}
			main_ppid=${all_proc_ppid[$i]}
			father_pid="$main_ppid"
		fi
	done
	if [[ -z "$main_fname" ]] || [[ -z "$main_ppid" ]]; 
	then
		echo "Proceso no encontrado en el sistema"
		exit 0
	fi
fi

# Gets father_fname
for ((i=0; $i<$n_all_proc_pid;i++));
do
	if [[ "${all_proc_pid[$i]}" -eq "$father_pid" ]];
	then 	
		father_fname="${all_proc_fname[$i]}"
	fi
done

echo "########################"
echo "######TOTAL: $n_all_proc_pid######"
echo "------$father_pid-------"
echo "------$father_fname-----"
echo "                       |"
echo "                       |"
echo "                       ########################"
echo "                       -------$main_pid--------"
echo "                       -------$main_fname------"
echo "                                                 |"
echo "                                                 |"
echo "                                                  #######################"
for ((i=0; $i<$n_all_proc_pid; i++));
do
	if [[ "${all_proc_ppid[$i]}" -eq "$main_pid" ]];
	then
		
	echo "                                                   ${all_proc_pid[$i]} - ${all_proc_fname[$i]}"
	fi
done
exit 0
